﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WXYW.BLL;
using WXYW.DAL;

namespace WXYW
{
    public partial class BJXXSupportCheck : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindForm();
            }
        }

        private void BindForm()
        {
            ApplicationProductService service = new ApplicationProductService();
            ApplicationProduct product = service.GetApplicationProductByID(long.Parse(Request.QueryString[Constants.QUERYSTR_PRODUCT_ID]));
            if (!product.ApplicationFormReference.IsLoaded)
            {
                product.ApplicationFormReference.Load();
            }
            if (!product.ApplicationForm.UserReference.IsLoaded)
            {
                product.ApplicationForm.UserReference.Load();
            }
            if (!product.ProductTypeReference.IsLoaded)
            {
                product.ProductTypeReference.Load();
            }

            contactLabel.Text = product.ApplicationForm.User.ContactPerson;
            companyLabel.Text = product.ApplicationForm.User.CompanyName;
            phoneNumberLabel.Text = product.ApplicationForm.User.UserPhone;
            cellPhoneLabel.Text = product.ApplicationForm.User.UserMobilePhone;
            faxLabel.Text = product.ApplicationForm.User.UserFax;
            addressLabel.Text = product.ApplicationForm.User.UserAddress;
            emailLabel.Text = product.ApplicationForm.User.UserEmail;
            agentLabel.Text = product.ApplicationForm.ProviderName;
            Label1.Text = product.ApplicationForm.ApplicationDateTime.Value.ToString("yyyy-MM-dd");
            Label2.Text = product.DealWithDateTime.HasValue ? product.DealWithDateTime.Value.ToString("yyyy-MM-dd") : "";

            //
            runningNumberLabel.Text = product.ApplicationForm.RunningNumber;
            spcodeLabel.Text = product.SPCode;
            productTypeLabel.Text = product.ReturnProductType;
            productSerivalNumberLabel.Text = product.ReturnSerialNumber;
            buyTimeLabel.Text = product.ProductPurchaseDateTime.Value.ToString("yyyy-MM-dd");
            statusLabel.Text = product.Status;
            repairTupeLabel.Text = product.ProductRepairType;
            problemDescriptionLabel.Text = product.ProductProblemDescription;
            problemTypeLabel.Text = product.ProblemType.Name;
            accessoryLabel.Text = product.ProductAppearance;
            versionNumberLabel.Text = product.ReturnProductVersion;

            //            
            UserService userservice = new UserService();
            if (product.ApplicationForm.AgentID.HasValue)
            {

                User agent = userservice.GetUserByID(product.ApplicationForm.AgentID.Value);
                Label4.Text = agent.ContactPerson;
                Label5.Text = agent.UserPhone;
            }

            //
            runningNumberLabel.Text = product.ApplicationForm.RunningNumber;
            spcodeLabel.Text = product.SPCode;
            productTypeLabel.Text = product.ProductType.ProductTypeName;
            productSerivalNumberLabel.Text = product.ProductSerialNumber;
            buyTimeLabel.Text = product.ProductPurchaseDateTime.Value.ToString("yyyy-MM-dd");
            statusLabel.Text = product.Status;
            repairTupeLabel.Text = product.ProductRepairType;
            problemDescriptionLabel.Text = product.ProductProblemDescription;
            problemTypeLabel.Text = product.ProblemType.Name;
            accessoryLabel.Text = product.ProductAppearance;
            versionNumberLabel.Text = product.ProductVersionNumber;

            // for buttons
            if (!string.IsNullOrEmpty(product.BJXXSuggestion))
            {
                checkStatusLabel.Text = "验证完毕";
                User currentUser = userservice.GetUserByID(ContextService.CurrentAccount.UserID);
                if (!currentUser.UserTypeReference.IsLoaded)
                {
                    currentUser.UserTypeReference.Load();
                }
                if (currentUser.UserType.ID == (int)RoleType.Administrator || currentUser.UserType.ID == (int)RoleType.SparePart ||
                    currentUser.UserType.ID == (int)RoleType.Engineer)
                {
                    okLinkButton.Enabled = true;
                }
            }

            // pictures            
            List<ApplicationPicture> list = product.ApplicationForm.ApplicationPicture.ToList();
            Table table = new Table();
            table.Rows.Add(new TableRow());
            table.Rows.Add(new TableRow());
            foreach (ApplicationPicture picture in list)
            {
                string docType = GetDocType(picture.PictureNameOnServer);
                TableCell celllImage = new TableCell();
                Image imageControl = new Image();
                imageControl.Height = 100;
                if (docType.ToLower() != "jpg" && docType.ToLower() != "bmp" && docType.ToLower() != "gif" && docType.ToLower() != "png")
                {
                    imageControl.ImageUrl = "image/" + "document.png";
                    imageControl.Attributes.Add("OnClick", "window.open('Picture/" + picture.PictureNameOnServer + "')");
                }
                else
                {
                    imageControl.ImageUrl = "Picture/" + picture.PictureNameOnServer;
                    imageControl.Attributes.Add("OnClick", "window.open('ImageDetail.aspx?Name=" + picture.PictureNameOnServer + "')");
                }

                celllImage.Controls.Add(imageControl);
                table.Rows[0].Cells.Add(celllImage);

                TableCell cellName = new TableCell();
                Label label = new Label();
                label.Text = picture.PictureName;
                cellName.Controls.Add(label);
                table.Rows[1].Cells.Add(cellName);
            }
            picturePanel.Controls.Add(table);

            // bind last send product information
            if (product.ApplicationForm.ParentBJXXNO.HasValue)
            {
                ApplicationService appservice = new ApplicationService();
                ApplicationForm parentForm = appservice.GetApplicationFormByID(product.ApplicationForm.ParentBJXXNO.Value);
                if (parentForm != null && !parentForm.ApplicationProduct.IsLoaded)
                {
                    parentForm.ApplicationProduct.Load();
                }

                if (parentForm.ApplicationProduct.Count > 0)
                {
                    lastproductserialnumberTextBox.Text = parentForm.ApplicationProduct.FirstOrDefault().ReplaceProductSerialNumber;
                    lastproducttypeTextBox.Text = parentForm.ApplicationProduct.FirstOrDefault().ReplaceProductType;
                    lastproductVersionTextBox.Text = parentForm.ApplicationProduct.FirstOrDefault().ReplaceProductVersion;
                    lastsendRemarkTextBox.Text = parentForm.ApplicationProduct.FirstOrDefault().Remark;
                }

                reSendPanel.Visible = true;
            }
        }

        private string GetDocType(string nameonserver)
        {
            if (!string.IsNullOrEmpty(nameonserver))
            {
                string[] nametype = nameonserver.Split('.');
                return nametype[1];
            }
            else
            {
                return string.Empty;
            }
        }

        protected void backLinkButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("BJXXListSupportCheck.aspx");
        }

        protected void okLinkButton_Click(object sender, EventArgs e)
        {
            ApplicationProductService service = new ApplicationProductService();
            ApplicationProduct product = service.GetApplicationProductByID(long.Parse(Request.QueryString[Constants.QUERYSTR_PRODUCT_ID]));


            product.Status = "备件完毕";

            // update applicationform 
            if (!product.ApplicationFormReference.IsLoaded)
            {
                product.ApplicationFormReference.Load();
            }
            product.ApplicationForm.Status = "备件完毕";

            service.UpdateProduct(product);
            Response.Redirect("BJXXListSupportCheck.aspx");
        }

        protected void checkLinkButton_Click(object sender, EventArgs e)
        {
            maintainRecordModalPopupExtender.Show();
            ClearWXForm();
            BindProductInfo();
        }

        protected void toRMALinkButton_Click(object sender, EventArgs e)
        {
            TurnToRMAForm();
            ClientScript.RegisterStartupScript(this.GetType(), "tip", "alert('成功转成RMA单');location.href='BJXXListSupportCheck.aspx';", true);
        }

        private void TurnToRMAForm()
        {
            ApplicationProductService service = new ApplicationProductService();
            ApplicationProduct product = service.GetApplicationProductByID(long.Parse(Request.QueryString[Constants.QUERYSTR_PRODUCT_ID]));
            ApplicationService appService = new ApplicationService();
            UserService userservice = new UserService();
            WXYW.DAL.User userentity = userservice.GetUserByName(System.Configuration.ConfigurationManager.AppSettings["BJKF"].ToString());
            ApplicationForm newForm = new ApplicationForm();
            newForm.ApplicationDateTime = DateTime.Now;
            //newForm.ApplicationCode = RunningNumberService.getr
            newForm.ApplicationType = "R";
            newForm.User = userentity;
            newForm.IsSubmit = true;
            newForm.Status = "待修";
            newForm.RunningNumber = RunningNumberService.GenerateApplicationNumber();

            if (!product.ProductTypeReference.IsLoaded)
            {
                product.ProductTypeReference.Load();
            }
            if (!product.ProblemTypeReference.IsLoaded)
            {
                product.ProblemTypeReference.Load();
            }
            if (!product.UserReference.IsLoaded)
            {
                product.UserReference.Load();
            }
            if (!product.User.ServiceStationReference.IsLoaded)
            {
                product.User.ServiceStationReference.Load();
            }
            ProductClassService classService = new ProductClassService();
            ProductType type = classService.GetProductTypeByName(product.ReturnProductType);
            ApplicationProduct newproduct = new ApplicationProduct
            {
                ProductType = type,
                ProductCount = 1,
                ProductSerialNumber = product.ReturnSerialNumber,
                ProductVersionNumber = product.ReturnProductVersion,
                ProblemType = product.ProblemType,
                ProductProblemDescription = product.ProductProblemDescription,
                ProductAppearance = product.ProductAppearance,
                ProductPurchaseDateTime = product.ProductPurchaseDateTime,
                DistributeDateTime = DateTime.Now,
                Status = "待修",
                User = product.User,
                ProductRepairType = "保内",
                BJXXRemark = product.BJXXRemark,
                BLXX = product.BLXX
            };
            newForm.ServiceStation = product.User.ServiceStation;
            newForm.ApplicationCode = RunningNumberService.GenerateRMANumber(product.User.ServiceStation.ForShort);
            newForm.DistributeDateTime = DateTime.Now;
            newForm.ReceiveDateTime = DateTime.Now;
            newForm.RMANOGenerateDateTime = DateTime.Now;
            newForm.ApplicationProduct.Add(newproduct);

            long applicationID = appService.AddApplication(newForm);

            appService.SubmitApplication(applicationID);
        }

        protected void saveMaintainLinkButton_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(suggestionTextBox.Text))
            {
                ApplicationProductService service = new ApplicationProductService();
                ApplicationProduct product = service.GetSimpleApplicatonProductByID(long.Parse(Request.QueryString[Constants.QUERYSTR_PRODUCT_ID]));
                product.BLXX = blxxTextBox.Text;
                product.BJXXIsReal = RadioButtonList.SelectedIndex == 0 ? true : false;
                product.BJXXRemark = bzTextBox.Text;
                //product.RepairCompleteDateTime = DateTime.Now; // Chen Pu: 2010-06-02 不能在这里保存维修完成时间
                if (!product.ProblemAnalyzeReference.IsLoaded)
                {
                    product.ProblemAnalyzeReference.Load();
                }
                if (product.ProblemAnalyze == null)
                {
                    product.ProblemAnalyze = new ProblemAnalyze();
                }
                product.ProblemAnalyze.A = getProblemAnalyzeA();
                product.ProblemAnalyze.B = getProblemAnalyzeB();
                product.ProblemAnalyze.C = getProblemAnalyzeC();
                product.ProblemAnalyze.D = getProblemAnalyzeD();
                product.ProblemAnalyze.E = getProblemAnalyzeE();

                product.BJXXSupportCheckTime = DateTime.Now;
                product.BJXXSuggestion = suggestionTextBox.Text;
                service.UpdateProduct(product);

                maintainRecordModalPopupExtender.Hide();
                checkStatusLabel.Text = "验证完毕啦";
            }
            else
            {
                tipLabel.Text = "请填写技术支持意见！";
            }
        }

        protected void uploadButton_Click(object sender, EventArgs e)
        {
            long applicationID = 0;
            string fileType = string.Empty;
            string fileName = string.Empty;
            string fileNameOnServer = string.Empty;
            if (FileUpload1.HasFile)
            {
                fileType = FileUpload1.FileName.Substring(FileUpload1.FileName.LastIndexOf("."));
                fileName = FileUpload1.FileName;
                fileNameOnServer = Guid.NewGuid() + fileType;
                FileUpload1.SaveAs(Server.MapPath("Picture/" + fileNameOnServer));
            }

            ApplicationProductService productservice = new ApplicationProductService();
            ApplicationProduct product = productservice.GetApplicationProductByID(long.Parse(Request.QueryString[Constants.QUERYSTR_PRODUCT_ID]));
            if (!product.ApplicationFormReference.IsLoaded)
            {
                product.ApplicationFormReference.Load();
            }
            applicationID = product.ApplicationForm.ApplicationID;

            if (applicationID > 0)
            {
                ApplicationService service = new ApplicationService();
                ApplicationForm form = service.GetApplicationFormByID(applicationID);
                ApplicationPicture picture = new ApplicationPicture
                {
                    PictureName = fileName,
                    PictureNameOnServer = fileNameOnServer,
                    Type = (int)PictureType.ConfirmProduct,
                    UploadPerson = ContextService.CurrentAccount.UserID
                };
                form.ApplicationPicture.Add(picture);
                service.UpdateApplication(form);

                Response.Redirect(Request.Url.ToString());
            }
        }


        private void BindProductInfo()
        {
            ApplicationProductService service = new ApplicationProductService();
            ApplicationProduct product = service.GetApplicationProductByID(long.Parse(Request.QueryString[Constants.QUERYSTR_PRODUCT_ID]));
            blxxTextBox.Text = product.BLXX;
            bzTextBox.Text = product.Remark;
            suggestionTextBox.Text = product.BJXXSuggestion;

            if (!product.ProblemAnalyzeReference.IsLoaded)
            {
                product.ProblemAnalyzeReference.Load();
            }

            if (product.ProblemAnalyze != null)
            {
                InitializeProblemAnalyze(product.ProblemAnalyze);
            }
        }

        private void ClearWXForm()
        {
            tipLabel.Text = "";
            blxxTextBox.Text = "";

            RadioButton1.Checked = false;
            RadioButton2.Checked = false;
            RadioButton3.Checked = false;
            RadioButton4.Checked = false;
            RadioButton5.Checked = false;
            RadioButton6.Checked = false;
            RadioButton7.Checked = false;
            RadioButton8.Checked = false;
            RadioButton9.Checked = false;
            RadioButton10.Checked = false;
            RadioButton11.Checked = false;
            RadioButton12.Checked = false;
            RadioButton13.Checked = false;
            bzTextBox.Text = "";
            Label1.Text = "";
        }

        private void InitializeProblemAnalyze(ProblemAnalyze problemAnalyze)
        {
            SetProblemAnalyzeA(problemAnalyze.A);
            SetProblemAnalyzeB(problemAnalyze.B);
            SetProblemAnalyzeC(problemAnalyze.C);
            SetProblemAnalyzeD(problemAnalyze.D);
            SetProblemAnalyzeE(problemAnalyze.E);
        }

        private string getProblemAnalyzeE()
        {
            string eStr = string.Empty;
            if (RadioButton11.Checked)
            {
                eStr = RadioButton11.Text;
            }
            else if (RadioButton14.Checked)
            {
                eStr = RadioButton14.Text;
            }
            else if (RadioButton15.Checked)
            {
                eStr = RadioButton15.Text;
            }
            else if (RadioButton16.Checked)
            {
                eStr = RadioButton16.Text;
            }
            return eStr;
        }

        private void SetProblemAnalyzeE(string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                if (value.Equals(RadioButton11.Text))
                {
                    RadioButton11.Checked = true;
                }
                else if (value.Equals(RadioButton14.Text))
                {
                    RadioButton14.Checked = true;
                }
                else if (value.Equals(RadioButton15.Text))
                {
                    RadioButton15.Checked = true;
                }
                else if (value.Equals(RadioButton16.Text))
                {
                    RadioButton16.Checked = true;
                }
            }
        }

        private string getProblemAnalyzeD()
        {
            string dStr = string.Empty;
            if (RadioButton10.Checked)
            {
                dStr = RadioButton10.Text;
            }

            return dStr;
        }

        private void SetProblemAnalyzeD(string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                if (value.Equals(RadioButton10.Text))
                {
                    RadioButton10.Checked = true;
                }
            }
        }

        private string getProblemAnalyzeC()
        {
            string cStr = string.Empty;
            if (RadioButton9.Checked)
            {
                cStr = RadioButton9.Text;
            }
            else if (RadioButton8.Checked)
            {
                cStr = RadioButton8.Text;
            }
            else if (RadioButton13.Checked)
            {
                cStr = RadioButton13.Text;
            }

            return cStr;
        }

        private void SetProblemAnalyzeC(string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                if (value.Equals(RadioButton9.Text))
                {
                    RadioButton9.Checked = true;
                }
                if (value.Equals(RadioButton8.Text))
                {
                    RadioButton8.Checked = true;
                }
                if (value.Equals(RadioButton13.Text))
                {
                    RadioButton13.Checked = true;
                }
            }
        }

        private string getProblemAnalyzeB()
        {
            string bStr = string.Empty;
            if (RadioButton7.Checked)
            {
                bStr = RadioButton7.Text;
            }
            else if (RadioButton6.Checked)
            {
                bStr = RadioButton6.Text;
            }
            else if (RadioButton5.Checked)
            {
                bStr = RadioButton5.Text;
            }
            else if (RadioButton12.Checked)
            {
                bStr = RadioButton12.Text;
            }
            return bStr;
        }

        private void SetProblemAnalyzeB(string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                if (value.Equals(RadioButton5.Text))
                {
                    RadioButton5.Checked = true;
                }
                if (value.Equals(RadioButton6.Text))
                {
                    RadioButton6.Checked = true;
                }
                if (value.Equals(RadioButton7.Text))
                {
                    RadioButton7.Checked = true;
                }
                if (value.Equals(RadioButton12.Text))
                {
                    RadioButton12.Checked = true;
                }
            }
        }

        private string getProblemAnalyzeA()
        {
            string aStr = string.Empty;
            if (RadioButton4.Checked)
            {
                aStr = RadioButton4.Text;
            }
            else if (RadioButton3.Checked)
            {
                aStr = RadioButton3.Text;
            }
            else if (RadioButton2.Checked)
            {
                aStr = RadioButton2.Text;
            }
            else if (RadioButton1.Checked)
            {
                aStr = RadioButton1.Text;
            }
            return aStr;
        }

        private void SetProblemAnalyzeA(string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                if (value.Equals(RadioButton1.Text))
                {
                    RadioButton1.Checked = true;
                }
                if (value.Equals(RadioButton2.Text))
                {
                    RadioButton2.Checked = true;
                }
                if (value.Equals(RadioButton3.Text))
                {
                    RadioButton3.Checked = true;
                }
                if (value.Equals(RadioButton4.Text))
                {
                    RadioButton4.Checked = true;
                }
            }
        }
    }
}
